# -*- coding: utf-8 -*-
import logging

from pylons import request, response, session, tmpl_context as c
from pylons.controllers.util import abort, redirect_to, forward
from pythonblog.lib.base import BaseController, render
from pythonblog.model import meta
import pythonblog.lib.helpers as h
import webhelpers.paginate as paginate
from pythonblog.model.account import *
from pythonblog.model.content import *
from pythonblog.model.navigation import *
from pythonblog.service import content_service
from pythonblog.service import user_service
from pythonblog.service import section_service

log = logging.getLogger(__name__)

class DispatcherController(BaseController):

    def __before__(self):
        sub_domain = self.get_sub_domain(request.environ)
        if self._is_home(sub_domain) or self.get_action(request.environ) == 'view':
            c.top_users = user_service.get_top_users()
            c.recommand_posts = content_service.get_recommand_posts()

    def dispatch(self):
        sub_domain = self.get_sub_domain(request.environ)
        if self._is_home(sub_domain):
            return self.view()
        else:
            return self._view_blog(sub_domain)

    def section(self, section_path):
        sub_domain = self.get_sub_domain(request.environ)
        if self._is_home(sub_domain):
            return self.view(section_path)
        else:
            return self._view_blog(sub_domain, section_path)

    def view(self, section_path='all', post_type='all', rank_type='new', time_duration='recent'):
        return self._section_display(section_path, post_type, rank_type, time_duration)

    def _section_display(self, section_path, post_type, rank_type, time_duration):
        self._set_menu(section_path, post_type, rank_type, time_duration)
        if section_path == 'all':
            section_id = -1
        else:
            section_id = section_service.get_section_by_path(section_path).id

        if post_type == 'all':
            type = -1
        else:
            type = section_service.get_type_by_path(post_type).id

        if time_duration == 'recent':
            time = -1
        else:
            if time_duration == 'day':
                time = 1
            if time_duration == 'week':
                time = 7
            if time_duration == 'month':
                time = 30
            if time_duration == 'year':
                time = 365

        page_count = 30
        if rank_type == 'new':
            c.posts = paginate.Page(
                filter(lambda post: self.post_filter(post, section_id, type, time), content_service.get_new_posts()),
                page=self._get_page(),
                items_per_page = page_count
            )
        if rank_type == 'hot':
            c.post_ids = paginate.Page(
                filter(lambda element: self.post_filter(content_service.get_post(element.id), section_id, type, time), content_service.get_hot_posts()),
                page=self._get_page(),
                items_per_page = page_count
            )
        if rank_type == 'total':
            c.post_ids = paginate.Page(
                filter(lambda element: self.post_filter(content_service.get_post(element.id), section_id, type, time), content_service.get_top_posts()),
                page=self._get_page(),
                items_per_page = page_count
            )

        return render('/derived/section/section.html')

    def _post_filter(post, section_id, type, time):
        if section_id != -1 and post.section_id != section_id:
            return False
        if type != -1 and post.type != type:
            return False
        if time != -1 and (h.now()-post.createDate).days >= time:
            return False
        return True

    post_filter = staticmethod(_post_filter)

    def _view_blog(self, userName, section_path='all'):
        userInfo = user_service.get_user(userName)
        if not userInfo:
            abort(404)
        if section_path == 'all':
            section_id = None
        else:
            section_id = section_service.get_section_by_path(section_path).id
        user_service.add_user_viewTimes(userInfo.userName)
        c.userInfo = userInfo
        c.blogInfo = content_service.get_blog_info(userInfo.id)
        c.posts = paginate.Page(
            content_service.get_posts(userInfo.id, section_id),
            page=self._get_page(),
            items_per_page = 20,
            item_count = None,
            sqlalchemy_session = meta.Session
        )
        return render('/derived/blog/blog.html')

    